package com.happy.controller;


import com.happy.common.utils.BeanHelper;
import com.happy.pojo.User;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    protected User user;


    @ModelAttribute
    public void init(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        this.request = request;
        this.response = response;
        this.session = session;

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser instanceof Map) {
            if (!CollectionUtils.isEmpty((HashMap) loginUser)) {
                try {
                    this.user = BeanHelper.mapToObject((HashMap) loginUser, User.class);
                } catch (Exception e) {
                    this.user = null;
                    e.printStackTrace();
                }
            }
        }
        if (loginUser instanceof User) {
            this.user = (User) loginUser;
        }
        if (loginUser == null) {
            this.user = null;
        }

        System.out.println(this.user);
    }

    /**
     * 获取登录用户的IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
